package swing.ui;

import java.util.Vector;

import javax.swing.tree.MutableTreeNode;


@SuppressWarnings("serial")
class ImmutableTreeNode extends SelectableTreeNode {
	private Vector oldParent;

	public ImmutableTreeNode() {
		oldParent = new Vector();
		children = new Vector();
		setSelected(true);
	}


	public void setThisParent() {
		for (int i = 0; i < children.size(); i++) {
			MutableTreeNode child = (MutableTreeNode) children.get(i);
			child.setParent(this);
		}
	}

	public void setOldParent() {
		for (int i = 0; i < children.size(); i++) {
			MutableTreeNode child = (MutableTreeNode) children.get(i);
			child.setParent((MutableTreeNode) oldParent.get(i));
		}
	}

	@SuppressWarnings("unchecked")
	public void add(SelectableTreeNode newChild) {
		if (newChild == null)
			throw new IllegalArgumentException("new child is null"); //$NON-NLS-1$

		oldParent.add(newChild.getParent());
		newChild.setParent(this);
		children.add(newChild);
	}


	public void refresh(SelectableTreeNode node) {
		int index = children.indexOf(node);

		if (index < 0) {
			if (node.getState() != TristateCheckBox.NOT_SELECTED)
				add(node);
		} else {
			if (node.getState() == TristateCheckBox.NOT_SELECTED)
				remove(index);
		}
	}

	public void removeAll() {
		for (int i = 0; i < children.size(); i++)
			remove(i);
	}

	public void remove(int index) {
		MutableTreeNode child = (MutableTreeNode) getChildAt(index);
		children.removeElementAt(index);
		// restore parent reference
		child.setParent((MutableTreeNode) oldParent.get(index));
		oldParent.remove(index);
	}

	@SuppressWarnings("unchecked")
	public void moveUp(int index) {
		if (index < 1 || index >= children.size())
			return;

		Object self = children.get(index);
		Object other = children.get(index - 1);
		children.set(index, other);
		children.set(index - 1, self);
		self = oldParent.get(index);
		other = oldParent.get(index - 1);
		oldParent.set(index, other);
		oldParent.set(index - 1, self);
	}

	@SuppressWarnings("unchecked")
	public void moveDown(int index) {
		if (index < 0 || index >= children.size() - 1)
			return;

		Object self = children.get(index);
		Object other = children.get(index + 1);
		children.set(index, other);
		children.set(index + 1, self);
		self = oldParent.get(index);
		other = oldParent.get(index + 1);
		oldParent.set(index, other);
		oldParent.set(index + 1, self);
	}
}
